<template>
    <div>
        <div class="w-form-header">
            <!-- <span>修改规格图</span> -->
            <div class="header" v-if="route.query.version">
                <div></div>
                <div class="title-box">
                    <span class="version" style="margin-right: 10px">
                        <!-- 審批人: {{ auditorUser || "暂无" }} -->
                        <el-button type="primary" @click="auditUserShow = true"
                            >查看审批人</el-button
                        >
                    </span>
                    <span class="version">
                        版本: {{ formData.version || "暂无" }}</span
                    >
                </div>
            </div>
            <div class="header" v-else>
                <div
                    v-if="
                        (formData.status == '0' || type == 'create') &&
                        userStore.userInfo.authority?.authorityId !== 1000
                    "
                >
                    <template v-if="isEditing">
                        <el-button type="primary" @click="isEditing = false"
                            >编辑</el-button
                        >
                    </template>
                    <template v-else>
                        <el-button
                            type="primary"
                            @click="save('0')"
                            :loading="submitLoading"
                            >保存</el-button
                        >
                        <el-button
                            type="success"
                            @click="save('2')"
                            :loading="saveLoading"
                            >提交</el-button
                        >
                    </template>
                    <el-button
                        type="primary"
                        v-if="formData.version >= 2"
                        @click="rollbackFun"
                        :loading="rollbackLoading"
                        >退回</el-button
                    >
                </div>
                <div v-else-if="formData.status == '2'">
                    <!-- <el-button type="primary" @click="setShenpi('同意')">提交</el-button>
                    <el-button type="danger" @click="setShenpi('拒绝')">退回</el-button> -->
                </div>
                <div
                    v-else-if="
                        formData.status == '1' &&
                        userStore.userInfo.authority?.authorityId !== 1000
                    "
                >
                    <!-- @click="isEditing = false" -->
                    <el-button
                        v-if="isEditing"
                        type="primary"
                        @click="editReasonDialogFun('edit')"
                        >编辑</el-button
                    >
                    <el-button
                        v-else
                        type="primary"
                        @click="save('1')"
                        :loading="submitLoading"
                        >保存</el-button
                    >
                    <el-button type="primary" @click="shengban" v-if="isEditing" 
                        >升版</el-button
                    >
                </div>
                <div v-else></div>
                <div class="title-box" v-if="type == 'update'">
                    <span class="version" style="margin-right: 10px">
                        <!-- 審批人: {{ auditorUser || "暂无" }} -->
                        <el-button type="primary" @click="auditUserShow = true"
                            >查看审批人</el-button
                        >
                    </span>
                    <span class="version">
                        版本: {{ formData.version || "暂无" }}</span
                    >
                    <span class="status">{{
                        formData.status == "1"
                            ? "完成"
                            : formData.status == "2"
                            ? "审批中"
                            : "草稿"
                    }}</span>
                </div>
            </div>
        </div>
        <div class="admin-content">
            <div class="gva-form-box">
                <el-descriptions
                    class="margin-top"
                    title="基本信息"
                    :column="4"
                    border
                >
                    <!-- 款式编号 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("kuanshibianhao.label")}:` }}
                            </div>
                        </template>
                        <div
                            style="
                                display: flex;
                                justify-content: space-between;
                                align-items: center;
                            "
                            v-if="!route.query.ddmsNum"
                        >
                            <el-select
                                v-model="formData.styleNum"
                                :clearable="true"
                                :placeholder="'点击查询'"
                                style="min-width: 150px; margin-right: 10px"
                                filterable
                                remote
                                :remote-method="getProductStylesListFn"
                                @change="styleNumChange"
                                @click="openCreateAndEdit"
                                disabled
                            >
                                <el-option
                                    v-for="item in productStylesList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                >
                                </el-option>
                            </el-select>
                            <el-icon @click="openCreateAndEdit">
                                <Search />
                            </el-icon>
                        </div>
                        <span v-else>{{ formData.styleNum }}</span>
                    </el-descriptions-item>
                    <!-- 客户品牌 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("kehupinpai.label")}:` }}
                            </div>
                        </template>
                        {{ formData.customerBrand }}
                    </el-descriptions-item>
                    <!-- 系列 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("xilie.label")}:` }}
                            </div>
                        </template>
                        {{ formData.series }}
                    </el-descriptions-item>

                    <!-- 审批流程 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("shenpiliucheng.label")}:` }}
                            </div>
                        </template>
                        <el-select
                            v-model="formData.approvalProcess"
                            :placeholder="il8n('shenpiliucheng.placeholder')"
                            :disabled="isEditing"
                        >
                            <el-option
                                v-for="item in dictOptions.approvalProcess"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-descriptions-item>
                    <!-- sbu -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("SBU.label")}:` }}
                            </div>
                        </template>
                        {{ formData.sbuNum }}
                    </el-descriptions-item>
                    <!-- 目标消费者 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("mubiaoxiaofeizhe.label")}:` }}
                            </div>
                        </template>
                        {{ formData.gender }}
                    </el-descriptions-item>
                    <!-- 图纸编号 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("tupianbianhao.label")}:` }}
                            </div>
                        </template>
                        {{ formData.drawingNum }}
                    </el-descriptions-item>
                    <!-- 创建人 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("chuangjianren.label")}:` }}
                            </div>
                        </template>
                        <span
                            v-if="
                                formData.createdUser &&
                                formData.createdUser.nickName
                            "
                        >
                            {{ formData.createdUser.nickName }}
                        </span>
                        <span v-else>{{ formData.createUser }}</span>
                    </el-descriptions-item>
                    <!-- 本厂款号 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("benchangkuanhao.label")}:` }}
                            </div>
                        </template>
                        {{ formData.localStyleNum }}
                    </el-descriptions-item>
                    <!-- 分类 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("fenlei.label")}:` }}
                            </div>
                        </template>
                        <el-select
                            v-model="formData.drawingCharacterCate"
                            :placeholder="il8n('fenlei.placeholder')"
                            :disabled="isEditing"
                            @change="drawingCharacterCateChange('change')"
                        >
                            <el-option
                                v-for="item in dictOptions.drawingCharacterCate"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-descriptions-item>
                    <!-- 结构 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("jiegou.label")}:` }}
                            </div>
                        </template>
                        <el-select
                            v-model="formData.structure"
                            :placeholder="il8n('jiegou.placeholder')"
                            :disabled="isEditing"
                        >
                            <el-option
                                v-for="item in dictOptions.structure"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-descriptions-item>
                    <!-- 创建时间 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("chuangjianshijian.label")}:` }}
                            </div>
                        </template>
                        {{
                            formData.CreatedAt
                                ? formatDate(
                                      formData.CreatedAt,
                                      "yyyy-MM-dd hh:mm:ss"
                                  )
                                : ""
                        }}
                    </el-descriptions-item>
                    <!-- 客户编号 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("kehubianhao.label")}:` }}
                            </div>
                        </template>
                        {{ formData.cumstomerNum }}
                    </el-descriptions-item>
                    <!-- 图纸分类 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("tuzhifenlei.label")}:` }}
                            </div>
                        </template>
                        <el-select
                            v-model="formData.drawingCate"
                            :placeholder="il8n('tuzhifenlei.placeholder')"
                            filterable
                            :disabled="isEditing"
                            @change="drawingCateChange"
                            @focus="drawingCateFocus"
                        >
                            <el-option
                                v-for="item in drawingCateOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                        </el-select>
                    </el-descriptions-item>
                    <!-- 尺码 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("chima.label")}:` }}
                            </div>
                        </template>
                        <el-select
                            v-model="formData.displaySize"
                            :placeholder="il8n('chima.placeholder')"
                            value-key="value"
                            :disabled="isEditing"
                        >
                            <el-option
                                v-for="item in displaySizeOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item"
                            >
                            </el-option>
                        </el-select>
                    </el-descriptions-item>
                    <!-- 更新人 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("gengxinren.label")}:` }}
                            </div>
                        </template>
                        <span
                            v-if="
                                formData.updatedUser &&
                                formData.updatedUser.nickName
                            "
                        >
                            {{ formData.updatedUser.nickName }}
                        </span>
                        <span v-else>{{ formData.updateUser }}</span>
                    </el-descriptions-item>
                    <!-- 客户款号 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("kehukuanhao.label")}:` }}
                            </div>
                        </template>
                        {{ formData.customerStyleNum }}
                    </el-descriptions-item>
                    <!-- 资料类型 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("ziliaoleixing.label")}:` }}
                            </div>
                        </template>
                        <el-select
                            v-model="formData.dataType"
                            :disabled="
                                formData.drawingCharacterCate == '概念规格图' ||
                                formData.drawingCharacterCate == '概念規格圖' ||
                                isEditing
                            "
                            :clearable="true"
                            :placeholder="''"
                            filterable
                            @change="dataTypeChange"
                        >
                            <template v-if="formData.drawingCate == '3D'">
                                <el-option
                                    v-for="item in dictOptions.drawingDataType"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                >
                                </el-option>
                            </template>
                            <template v-else>
                                <el-option
                                    v-for="item in dictOptions.drawingDataType.slice(
                                        0,
                                        3
                                    )"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                >
                                </el-option>
                            </template>
                        </el-select>
                    </el-descriptions-item>
                    <!-- 镜架材质 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("jingjiacaizhi.label")}:` }}
                            </div>
                        </template>
                        {{ formData?.extend?.frameMaterials }}
                    </el-descriptions-item>
                    <!-- 更新时间 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                        :span="2"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("gengxinshijian.label")}:` }}
                            </div>
                        </template>
                        {{
                            formData.UpdatedAt
                                ? formatDate(
                                      formData.UpdatedAt,
                                      "yyyy-MM-dd hh:mm:ss"
                                  )
                                : ""
                        }}
                    </el-descriptions-item>
                    <!-- 自制配件 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                        :span="4"
                        style="width: 100%"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("zizhipeijian.label")}:` }}
                            </div>
                        </template>
                        <el-checkbox
                            v-for="item in formData.selfMadeAccessory"
                            :key="item.value"
                            :label="item.label"
                            v-model="item.checked"
                            :disabled="isEditing"
                        >
                            {{ item.label }}
                        </el-checkbox>
                    </el-descriptions-item>
                    <!-- 备注 -->
                    <el-descriptions-item
                        label-class-name="my-label"
                        class-name="my-content"
                        :span="4"
                    >
                        <template #label>
                            <div class="cell-item">
                                {{ `${il8n("beizhu.label")}:` }}
                            </div>
                        </template>
                        <el-input
                            v-model="formData.note"
                            :placeholder="il8n('beizhu.placeholder')"
                            :clearable="true"
                            type="textarea"
                            style="width: 100%"
                            :disabled="isEditing"
                            :autosize="{ minRows: 1 }"
                            :maxlength="500"
                            show-word-limit
                        />
                    </el-descriptions-item> 
                    <el-descriptions-item
                    v-if="route.query.ID"
                        label-class-name="my-label"
                        class-name="my-content"
                    >
                        <template #label>
                            <div class="cell-item">
                                第一版本创建时间
                            </div>
                        </template>
                       <span v-if="formData.FirstCreatedAt">{{formatDate(formData.FirstCreatedAt )=="1-01-01" ? '' : formatDate(formData.FirstCreatedAt ) }}</span>
                    </el-descriptions-item>
                    
                </el-descriptions>
            </div>
            <div class="gva-form-box">
                <div class="w-form-box">
                    <div class="list-header">
                        图纸列表
                        <!-- <el-button
                            v-if="!route.query.version"
                            :disabled="isEditing"
                            :loading="uploadLoading"
                            @click="uploadDialogVisible = true"
                            type="primary"
                            >上传图纸</el-button
                        > -->
                    </div>
                    <div>
                        <el-table
                            :data="formData.drawingLists"
                            border
                            style="width: 100%"
                        >
                            <el-table-column
                                type="index"
                                label="序号"
                                width="60"
                            />
                            <el-table-column
                                label="图纸名称"
                                prop="drawingName"
                                min-width="300"
                            >
                                <template #default="scope">
                                    <span>{{ scope.row.drawingName }}</span
                                    ><span
                                        style="
                                            margin-left: 20px;
                                            color: #4d70ff;
                                        "
                                        v-if="scope.row.lockStatus == 'lock'"
                                        >{{
                                            scope.row.drawingUser
                                        }}正在修改</span
                                    >
                                </template>
                            </el-table-column>
                            <el-table-column label="图纸类型" min-width="130">
                                <template #default="scope">
                                    <el-select
                                        v-model="scope.row.drawingType"
                                        :placeholder="'选择类型'"
                                        @change="dTypeChange(scope.row)"
                                        :disabled="isEditing"
                                    >
                                        <el-option
                                            v-for="item in dictOptions.drawingCate"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value"
                                        >
                                        </el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column
                                label="上传时间"
                                prop="CreatedAt"
                                min-width="180"
                            >
                                <template #default="{ row }">
                                    {{
                                        formatDate(
                                            row.CreatedAt,
                                            "yyyy-MM-dd hh:mm:ss"
                                        )
                                    }}
                                </template>
                            </el-table-column>
                            <el-table-column
                                label="操作"
                                width="230"
                                fixed="right"
                            >
                                <template #default="{ row, $index }">
                                    <el-space wrap>
                                        <a
                                            @click="delImage(row, $index)"
                                            style="color: red; cursor: pointer"
                                            v-if="
                                                !isEditing &&
                                                '完成状态的删除按钮' in
                                                    btnAuth &&
                                                formData.status == '1'
                                            "
                                            >删除</a
                                        >
                                        <a
                                            @click="delImage(row, $index)"
                                            style="color: red; cursor: pointer"
                                            v-if="
                                                !isEditing &&
                                                '除完成状态的删除按钮' in
                                                    btnAuth &&
                                                formData.status != '1'
                                            "
                                            >删除</a
                                        >
                                        <!-- <a v-if="'drawView' in btnAuth"
                                            :href="`dayuer-cadopen:${path1}${row.fileUrl}?ID=${row.ID}&action=view&X-Token=${xToken}`">查看</a> -->
                                        <a
                                            :href="`dayuer-cadopen:${path1}${row.fileUrl}?ID=${row.ID}&action=edit&X-Token=${xToken}`"
                                            v-if="
                                                !isEditing &&
                                                'drawEdit' in btnAuth
                                            "
                                            >编辑</a
                                        >
                                        <a
                                            v-if="'drawDownload' in btnAuth"
                                            href="javascript:void(0)"
                                            @click="downloadFile(row)"
                                            >下载</a
                                        >
                                    </el-space>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div v-if="!isEditing">
                        <el-upload
                            :action="`${path}/fileUploadAndDownload/upload`"
                            :on-change="checkFile"
                            drag
                            :multiple="true"
                            :on-error="uploadError"
                            :on-success="uploadSuccess"
                            :show-file-list="false"
                            style="margin-left: 25px; display: inline"
                            :headers="{
                                'x-token': xToken,
                                'x-user-id': xUserId,
                                Authorization: `Bearer ${xToken}`,
                            }"
                        >
                            <div style="color: #999999">
                                拖拽到此区域即可完成批量上传
                            </div>
                        </el-upload>
                    </div>
                </div>
            </div>
            <div class="gva-form-box">
                <div class="w-form-box">
                    <div class="list-header">历史修改备注</div>
                    <el-table
                        :data="formData.modifyNotes"
                        border
                        style="width: 100%"
                    >
                        <el-table-column
                            type="index"
                            label="序号"
                            width="80px"
                        />
                        <el-table-column
                            label="更改内容"
                            prop="reason"
                        ></el-table-column>
                        <el-table-column label="更改原因" prop="content">
                        </el-table-column>
                        <el-table-column
                            label="详细说明"
                            prop="detail"
                        ></el-table-column>
                        <el-table-column label="更新时间" prop="">
                            <template #default="scope">
                                <span>
                                    {{
                                        formatDate(
                                            scope.row.UpdatedAt,
                                            "yyyy-MM-dd hh:mm:ss"
                                        )
                                    }}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column label="更新人" prop="updateUser">
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>

        <!-- 添加修改备注 -->
        <el-dialog
            v-model="editReasonDialogShow"
            destroy-on-close
            width="50%"
            title="添加修改备注"
        >
            <el-form
                ref="editReasonDialogRef"
                :rules="editRule"
                inline
                :model="editReasonForm"
            >
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="内容分类：" prop="content">
                            <el-checkbox-group v-model="editReasonForm.content">
                                <el-checkbox
                                    v-for="item in contentCateOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                    style="width: 100%"
                                />
                            </el-checkbox-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="原因分类：" prop="reason">
                            <el-checkbox-group v-model="editReasonForm.reason">
                                <el-checkbox
                                    v-for="item in reasonCateOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                    style="width: 100%"
                                />
                            </el-checkbox-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item
                            label="详细说明："
                            style="width: 100%"
                            prop="detail"
                        >
                            <textarea
                                v-model="editReasonForm.detail"
                                :rows="5"
                                style="width: 90%"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button
                        type="primary"
                        v-if="editStatus == 'shenban'"
                        @click="shenbanComfirm"
                        :disabled="editComfirmdis"
                        >确定</el-button
                    >
                    <el-button
                        type="primary"
                        v-if="editStatus == 'edit'"
                        @click="editComfirm"
                        
                        >确定</el-button
                    >
                    <el-button @click="editReasonDialogShow = false"
                        >取消</el-button
                    >
                </div>
            </template>
        </el-dialog>

        <!-- 附件长传弹窗 -->
        <!-- <el-dialog v-model="uploadDialogVisible" title="文件上传" width="800">
            <el-upload
                :action="`${path}/fileUploadAndDownload/upload`"
                :before-upload="checkFile"
                drag
                :on-error="uploadError"
                :on-success="uploadSuccess"
                :show-file-list="false"
                style="margin-left: 25px; display: inline"
                :headers="{
                    'x-token': xToken,
                    'x-user-id': xUserId,
                    Authorization: `Bearer ${xToken}`,
                }"
            >
                <el-button :loading="uploadLoading" type="primary"
                    >上传</el-button
                >
            </el-upload>
        </el-dialog> -->
        <!-- 审批人 -->
        <el-dialog v-model="auditUserShow" title="审批信息" width="200">
            <el-table
                :data="formData.currOwners"
                border
                style="width: 100%"
                class="table-style-1"
            >
                <!-- <el-table-column type="index" label="序号" width="80px" /> -->
                <el-table-column label="审批人" prop="name"></el-table-column>
                <!-- <el-table-column label="审批时间" prop="content">
                </el-table-column> -->
            </el-table>
        </el-dialog>

        <styleNumSearch
            v-if="styleNumDialogShow"
            @closeDialog="closeDialog"
            @selectStyleNum="selectStyleNum"
        >
        </styleNumSearch>
    </div>
</template>

<script setup>
import {
    createDdmsSpecDrawing,
    updateDdmsSpecDrawing,
    findDdmsSpecDrawing,
    updateDdmsSpecDrawingStatus,
    getDdmsSpecDrawingList,
    shenpi,
    updateDdmsSpecDrawingVersion,
    findDdmsSpecDrawingHistory,
    rollbackDdmsSpecDrawingVersion,
} from "@/api/plmDdmsSpecDrawing";
import { createDdmsSpecDrawingNote } from "@/api/ddmsSpecDrawingNote.js";
import { getSysDictionaryDetailList } from "@/api/sysDictionaryDetail"; // 获取字典
import { getDesignDrawingCategoryList } from "@/api/confDesignDrawingCategory.js";
import { getConceptDrawingCategoryList } from "@/api/confConceptDrawingCategory.js";
import {
    getProductStylesList,
    findProductStyles,
} from "@/api/plmProductStyles";
import {
    getDrawingCategoryList,
    getSizesAndSpecs,
    getWorkflowDefList,
} from "@/api/drawingCategory";
import { deleteDdmsSpecDrawingList } from "@/api/ddmsSpecDrawingList";
import { createApplication } from "@/api/workflow";
import { findProductSpecSize } from "@/api/productSpecSize";
import LTable from "@/components/LTable/LTable.vue";
import styleNumSearch from "@/components/styleNumSearch/styleNumSearch.vue";
import { useUserStore } from "@/pinia/modules/user";
import { useBtnAuth } from "@/utils/btnAuth";
import { downloadFilePost } from "@/api/comment.js";
const btnAuth = useBtnAuth();
defineOptions({
    name: "DdmsSpecDrawingView",
});
// 全量引入格式化工具 请按需保留
import { formatDate } from "@/utils/format";
import { downloadImage } from "@/utils/downloadImg";

// 自动获取字典
import { ref, reactive, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getDictFunc } from "@/utils/format";
import { emitter } from "@/utils/bus.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { isVideoMime, isImageMime, isDWG } from "@/utils/image";
import { useDict } from "@/utils/dictionary";
import { useI18n } from "vue-i18n";
import { deepClone2 } from "@/utils/tool.js";
import axios from "axios";

const { t: il8n } = useI18n();
const basePath = ref(import.meta.env.VITE_BASE_PATH);

const route = useRoute();
const router = useRouter();

// 款式编号列表
const productStylesList = ref([]);
const type = ref("");
const auditorUser = ref("");
const formData = ref({
    drawingLists: [], //图纸列表
    styleNum: "",
    drawingCate: "", //图纸分类
    dataType: "", //资料类型
    selfMadeAccessory: [], // 自制配件
});
const saveLoading = ref(false);
const submitLoading = ref(false);
const dictOptions = ref({
    // 审批流程
    approvalProcess: [
        // { label: "0 設計規格客圖流程", value: "0 設計規格客圖流程" },
        // { label: "0設計規格ST101流程", value: "0設計規格ST101流程" },
        // { label: "1 設計規格INHSE流程", value: "1 設計規格INHSE流程" },
        // { label: "3 3D圖流程 UG", value: "3 3D圖流程 UG" },
        // { label: "3 注塑部2D圖紙確認", value: "3 注塑部2D圖紙確認" },
        // { label: "3D-客戶参考圖", value: "3D-客戶参考圖" },
        // { label: "3Win-wiN组图纸", value: "3Win-wiN组图纸" },
    ],
    // 结构
    structure: [],
    // 图纸类型
    drawingCate: [],
    //分类
    drawingCharacterCate: [],
    // 资料类型
    drawingDataType: [],
});
// 尺码
const displaySizeOptions = ref([]);
// 图纸分类
const drawingCateOptions = ref([]);
const uploadDialogVisible = ref(false);
const isEditing = ref(true);
const auditUserShow = ref(false);
const auditUserList = ref([]);
const editRule = ref({
    content: [{ required: true, message: "请选择", trigger: "change" }],
    reason: [{ required: true, message: "请选择", trigger: "change" }],
    detail: [{ required: true, message: "输入说明", trigger: "blur" }],
});
const editReasonDialogRef = ref();

const updateDdmsSpecDrawingStatusFun = () => {
    updateDdmsSpecDrawingStatus({ action: "edit" }).then((res) => {
        if (res.code == 0) {
            console.log("res", res);
        }
    });
};

// 初始化方法
const init = async () => {
    // isEditing.value = true;
    // 建议通过url传参获取目标数据ID 调用 find方法进行查询数据操作 从而决定本页面是create还是update 以下为id作为url参数示例
    if (route.query.ddmsNum && route.query.version) {
        isEditing.value = true;
        findDdmsSpecDrawingHistory({
            ddmsNum: route.query.ddmsNum,
            version: route.query.version,
        }).then((res) => {
            if (res.code == 0) {
                formData.value = res.data.reddmsSpecDrawing;
            }
        });
    } else if (route.query.ddmsNum) {
        const res = await findDdmsSpecDrawing({ ddmsNum: route.query.ddmsNum });
        if (res.code === 0) {
            if (res.data.auditorUser && res.data.auditorUser.length) {
                auditorUser.value = res.data.auditorUser
                    .map((item) => item.name)
                    .join(",");
            }
            formData.value = res.data.reddmsSpecDrawing;
            if (
                formData.value.workflowLog &&
                formData.value.workflowLog.operator.nickName
            ) {
                formData.value["currOwners"] = [
                    { name: formData.value.workflowLog.operator.nickName },
                ];
            }
            formData.value["drawingLists"] = [];
            type.value = "update";
            // 获取尺码
            getSizesAndSpecs({
                styleNum: formData.value.styleNum,
                searchType: "ddmsSpecDrawing",
            }).then((res) => {
                displaySizeOptions.value = res.data.sizes;
                if (res.data.specs) {
                    let partList = deepClone2(res.data.specs);
                    partList.forEach((p) => {
                        let idx = formData.value.selfMadeAccessory.findIndex(
                            (p1) => {
                                return p1.value == p.value;
                            }
                        );
                        if (idx == -1) {
                            formData.value.selfMadeAccessory.push(p);
                        }
                    });
                    // console.log(
                    //     "formData.value.selfMadeAccessory",
                    //     formData.value.selfMadeAccessory
                    // );
                    formData.value.selfMadeAccessory =
                        formData.value.selfMadeAccessory.filter((item) => {
                            // console.log("dd", item.value);
                            // let idx = partList.filter(p2=>{
                            //     // console.log("dd",item.value,"==",p2.value)
                            //     return p2.value != item.value
                            // })
                            let flag = partList.some((item2) => {
                                return item2.value === item.value;
                            });
                            if (!item.checked) {
                                return flag;
                            } else {
                                return true;
                            }
                        });
                }
                // formData.value.selfMadeAccessory = res.data.specs;
            });
            // 获取款式详情
            if (formData.value.styleNum) {
                findProductStyles({
                    styleNum: formData.value.styleNum,
                }).then((res) => {
                    let m = res.data.reproductStyles;
                    formData.value["targetConsumers"] = m.gender;
                    formData.value["customerBrand"] = m.customerBrand;
                    formData.value["series"] = m.series;
                    formData.value["sbuNum"] = m.sbuNum;
                    formData.value["localStyleNum"] = m.localStyleNum;
                    formData.value["customerStyleNum"] = m.customerStyleNum;
                    formData.value["cumstomerNum"] = m.cumstomerNum;
                    formData.value["gender"] = m.gender;
                });
            }
            // 规格图
            getDdmsSpecDrawingList({
                ID: formData.value.ID,
                styleNum: formData.value.styleNum,
                // accessoryNum: JSON.stringify(formData.value.selfMadeAccessory),
                sizeNum: formData.value.displaySize?.value || "",
                ddmsNum: formData.value.ddmsNum || "",
            }).then((res) => {
                if (res.code == 0) {
                    formData.value["drawingLists"] =
                        res.data.list[0]?.drawingLists || [];
                }
            });
            drawingCharacterCateChange("init");
        }
    } else {
        type.value = "create";
        isEditing.value = false;
    }
};

init();

// 保存按钮
const save = async (val) => {
    let res;
    let submitForm = Object.assign({}, formData.value);
    if (!submitForm.styleNum) {
        ElMessage({
            type: "warning",
            message: "请选择款式编号",
        });
        return;
    }
    if (!submitForm["displaySize"]) {
        submitForm["displaySize"] = {};
    }
    if (!submitForm["selfMadeAccessory"]) {
        submitForm["selfMadeAccessory"] = [];
    }
    // 校验不能为空
    if (val == "1" || val == "2" || val == "0") {
        let str = "";
        if (!submitForm.drawingCharacterCate) {
            str += "分类,";
        }
        if (!submitForm.drawingCate) {
            str += "图纸分类,";
        }
        if (
            !submitForm.dataType &&
            (formData.drawingCharacterCate != "概念规格图" ||
                formData.drawingCharacterCate != "概念規格圖")
        ) {
            str += " 资料类型,";
        }
        if (JSON.stringify(submitForm.displaySize) == "{}") {
            str += "尺码,";
        }
        if (!submitForm.structure) {
            str += "结构,";
        }
        if (!submitForm.approvalProcess) {
            str += "审批流程,";
        }
        if (str != "") {
            ElMessage({
                type: "error",
                message: str + "不能为空",
                duration: 6000,
            });
            return;
        }
    }
    if (val == "0") {
        submitForm["status"] = "0";
        submitLoading.value = true;
    } else if (val == "1") {
        submitForm["status"] = "1";
        saveLoading.value = true;
    } else if (val == "2") {
        if (!submitForm.approvalProcess) {
            ElMessage({
                type: "error",
                message: "请选择审批流程!",
            });
            return;
        }
        if (!submitForm.drawingLists || submitForm.drawingLists.length == 0) {
            ElMessage({
                type: "error",
                message: "沒有上圖紙不允許提交!",
            });
            return;
        }
        submitForm["status"] = "2";
        saveLoading.value = true;
    }

    if (submitForm.displaySize?.value) {
        submitForm.displaySize["checked"] = true;
    }
    if (type.value == "create") {
        createDdmsSpecDrawing(submitForm)
            .then((res) => {
                submitLoading.value = false;
                saveLoading.value = false;
                isEditing.value = false;
                if (res.code === 0) {
                    submitForm = {};
                    formData.value = {
                        drawingLists: [], //图纸列表
                        styleNum: "",
                        drawingCate: "", //图纸分类
                        dataType: "", //资料类型
                        selfMadeAccessory: [], // 自制配件
                    };
                    // 初始化分类
                    formData.value.drawingCharacterCate =
                        dictOptions.value.drawingCharacterCate[1].label;
                    drawingCharacterCateChange();
                    if (val == 2) {
                        // const params = {
                        //     workflowdef_id: Number(submitForm.approvalProcess),
                        //     title: dictOptions.value.approvalProcess.filter(
                        //         (item) => item.value == submitForm.approvalProcess
                        //     )[0].label,
                        //     detail_url: `/#/layout/ddmsSpecDrawingView?ddmsNum=${res.data.ddmsNum}&subTitle=${res.data.drawingNum}&isView=true`,
                        //     notify_url_approved: res.data.notifyUrlApproved,
                        //     notify_url_rejected: res.data.notifyUrlRejected,
                        //     appName:'spec_ddms',
                        //     projectNum:res.data.ddmsNum,
                        // };
                        // const result = await createApplication(params);
                        // if (result.code == 0) {
                        emitter.emit("closeThisPage", {
                            path: "/layout/ddmsSpecDrawingView",
                            query: {
                                ddmsNum: res.data.ddmsNum,
                                subTitle: res.data.drawingNum,
                            },
                        });
                        ElMessage({
                            type: "success",
                            message: "创建成功",
                        });
                        // }
                    } else {
                        if (res.code === 0) {
                            emitter.emit("closeThisPage", {
                                path: "/layout/ddmsSpecDrawingView",
                                query: {
                                    ddmsNum: res.data.ddmsNum,
                                    subTitle: res.data.drawingNum,
                                },
                            });
                            ElMessage({
                                type: "success",
                                message: "创建成功",
                            });
                        }
                    }
                }
            })
            .catch((err) => {
                submitLoading.value = false;
                saveLoading.value = false;
            });
    } else {
        // if (!submitForm.drawingLists || submitForm.drawingLists.length > 0 && submitForm.drawingCate == '2D'){
        //     let index = submitForm.drawingLists.findIndex(res=>{
        //         return res.drawingType == '中文'
        //     })
        //     if(index != -1){
        //         let dName = submitForm.drawingLists[index].drawingName
        //         let n = dName.split('-')[dName.split('-').length-1].split('.')[0]
        //         console.log("nn",n)
        //         if(+n !== +submitForm.version){
        //             ElMessage({
        //                 type: "warning",
        //                 message: "2D中文图纸文件名的末尾版本要和当前版本号一致",
        //             });
        //             submitLoading.value = false;
        //             saveLoading.value = false;
        //             return
        //         }
        //     }
        // }
        if (val == 2) {
            // const params = {
            //     workflowdef_id: Number(submitForm.approvalProcess),
            //     title: dictOptions.value.approvalProcess.filter(
            //         (item) => item.value == submitForm.approvalProcess
            //     )[0].label,
            //     detail_url: `/#/layout/ddmsSpecDrawingView?ddmsNum=${formData.value.ddmsNum}&subTitle=${formData.value.drawingNum}&isView=true`,
            //     notify_url_approved: formData.value.notifyUrlApproved,
            //     notify_url_rejected: formData.value.notifyUrlRejected,
            //     appName: "spec_ddms",
            //     projectNum: formData.value.ddmsNum,
            // };
            // const result = await createApplication(params);
            // if (result.code != 0) {
            //     ElMessage({
            //         type: "warning",
            //         message: "审批流错误,请联系管理员!",
            //     });
            //     return;
            // }
        }
        res = await updateDdmsSpecDrawing(submitForm);
        saveLoading.value = false;
        submitLoading.value = false;
        editReasonDialogShow.value = false;
        if (res.code === 0) {
            // emitter.emit("closeThisPage", { path: "/layout/ddmsSpecDrawing" });
            ElMessage({
                type: "success",
                message: "更改成功",
            });
            if (val == "0" || val == "1") {
                init();
                if (val == "1") {
                    isEditing.value = true;
                }
            } else {
                emitter.emit("closeThisPage", {
                    path: "/layout/ddmsSpecDrawing",
                });
            }
        }
    }
};

// 获取款式列表
async function getProductStylesListFn(keyword) {
    const res = await getProductStylesList({
        page: 1,
        pageSize: 50,
        styleNum: keyword,
        status: "1",
    });
    if (res.code === 0) {
        productStylesList.value = res.data.list.map((rdlm) => {
            rdlm["value"] = rdlm.styleNum;
            rdlm["label"] = rdlm.styleNum;
            return rdlm;
        });
    }
}

// 删除图片列表
const delImage = async (row, index) => {
    console.log(row, index);
  
    ElMessageBox.confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then (async() => {
        if (row.ID && formData.value.status == 0) {
            let res = await deleteDdmsSpecDrawingList({ ID: row.ID });
  

        if (res.code != 0) {
            // ElMessage({
            //     type: "error",
            //     message: res.msg,
            // });
            return;
        }
       
        ElMessage({
          message: '删除成功',
          type: 'success',
        })
    }
        if (row.drawingType == "中文") {
            formData.value["drawingNum"] = "";
        }
        formData.value.drawingLists.splice(index, 1);
    });
};

// 图纸分类改变
const drawingCharacterCateChange = (type) => {
    if (type == "change") {
        drawingCateOptions.value = []; // 图纸分类
        formData.value.drawingCate = ""; // 图纸分类
        // formData.value.displaySize = null; // 尺码
        formData.value.dataType = ""; // 资料类型
    }
    let drawingCharacterCate = formData.value.drawingCharacterCate;
    if (
        drawingCharacterCate == "概念规格图" ||
        drawingCharacterCate == "概念規格圖"
    ) {
        getConceptDrawingCategoryListFun();
    } else {
        drawingCateOptions.value = [
            { label: "2D", value: "2D" },
            { label: "3D", value: "3D" },
        ];
    }
};

const drawingCateFocus = () => {
    if (!formData.value.drawingCharacterCate) {
        ElMessage({ type: "warning", message: "请先选择分类" });
        return;
    }
};
// 图纸分类改变
const drawingCateChange = (val) => {
    formData.value.dataType = "";
    // formData.value.displaySize = null;
};
// 资料类型改变
const dataTypeChange = () => {
    // formData.value.displaySize = null;
};

// 分页获取--概念图纸分类 库列表
const getConceptDrawingCategoryListFun = () => {
    getSysDictionaryDetailList({
        page: 1,
        pageSize: 99,
        sysDictionaryID: 59,
    }).then((res) => {
        if (res.code === 0) {
            drawingCateOptions.value = res.data.list
                .map((item) => {
                    return {
                        label: item.value,
                        value: item.value,
                        dataType: item.label,
                        displaySizeShow: item.extend,
                    };
                })
                .filter((res) => {
                    return !!res.value;
                });
            if (formData.value.drawingCate) {
                drawingCateChange(formData.value.drawingCate);
            }
        }
    });
};

// 获取审批流
const getWorkflowDefListFun = () => {
    getWorkflowDefList({ keyword: "spec_ddms" }).then((res) => {
        if (res.code == 0) {
            dictOptions.value.approvalProcess = res.data.list?.map((item) => {
                return {
                    label: item.name,
                    value: item.ID + "",
                };
            });
        }
    });
};

// 上传图片
const uploadLoading = ref(false);
const path = ref(import.meta.env.VITE_BASE_API);
const filePath = import.meta.env.VITE_FILE_API + "/";
const path1 = ref(import.meta.env.VITE_BASE_API + "/");
const downloadPath = ref(import.meta.VITE_BASE_PATH + "/");

const userStore = useUserStore();
const xToken = ref("");
const xUserId = ref("");
xToken.value = userStore.token;
xUserId.value = userStore.userInfo.ID;

// 上传检查
const checkFile = (file) => {
    uploadLoading.value = true;
    const isLt500K = file.size / 1024 / 1024 < 0.5; // 500K, @todo 应支持在项目中设置
    const isLt5M = file.size / 1024 / 1024 < 5; // 5MB, @todo 应支持项目中设置
    const isVideo = isVideoMime(file.type);
    const isImage = isImageMime(file.type);
    const isDwg = isDWG(file);
    let pass = true;
    // if (!isVideo && !isImage && !isDwg) {
    //     ElMessage.error(
    //         "上传图片只能是 jpg,png,svg,webp,dwg 格式, 上传视频只能是 mp4,webm 格式!"
    //     );
    //     uploadLoading.value = false;
    //     pass = false;
    // }
    // if (!isLt5M && isVideo) {
    //     ElMessage.error("上传视频大小不能超过 5MB");
    //     uploadLoading.value = false;
    //     pass = false;
    // }
    // if (!isLt500K && isImage) {
    //     ElMessage.error("未压缩的上传图片大小不能超过 500KB，请使用压缩上传");
    //     uploadLoading.value = false;
    //     pass = false;
    // }
    // return pass;
    return true;
};
// 上传成功
const uploadSuccess = (res) => {
    const { data } = res;
    uploadLoading.value = false;
    if (res.code != 0) {
        ElMessage({ type: "error", message: res.msg });
        return;
    }
    if (data.file) {
        // emit('on-success', data.file.url)
        let drawingType = "";
        let list1 = formData.value.drawingLists.filter((item) => {
            return item.drawingType == "中文";
        });
        let list2 = formData.value.drawingLists.filter((item) => {
            return item.drawingType == "英文";
        });
        if (list1.length == 0) {
            drawingType = "中文";
            formData.value["drawingNum"] = data.file.name.split(".")[0];
        } else if (list2.length == 0) {
            drawingType = "英文";
        } else {
            drawingType = "参考";
        }
        formData.value.drawingLists.push({
            drawingName: data.file.name, //图纸名称
            fileUrl: data.file.url, //文件路径
            CreatedAt: data.file.CreatedAt,
            drawingType: drawingType,
        });
        uploadDialogVisible.value = false;
        ElMessage({
            type: "success",
            message: "上传成功",
        });
    }
};
// 上传失败
const uploadError = () => {
    ElMessage({
        type: "error",
        message: "上传失败",
    });
    uploadLoading.value = false;
};

// 下载
const downloadFile = (row) => {
    // let fileUrl;
    // if (
    //     row.fileUrl.indexOf("http://") > -1 ||
    //     row.fileUrl.indexOf("https://") > -1
    // ) {
    //     fileUrl = row.fileUrl;
    // } else {
    //     fileUrl = path1.value + row.fileUrl;
    // }
    let params = {
        drawingName: row.drawingName,
        fileUrl: row.fileUrl,
    };
    downloadFilePost(params).then((data) => {
        if (data.response && data.response.status == 404) {
            ElMessage({
                type: "warning",
                message: "文件不存在",
            });
            return;
        }
        let blob = new Blob([data.data], {});
        const fileName = row.drawingName;
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link); // 下载完成移除元素
        window.URL.revokeObjectURL(url); // 释放掉blob对象
    });

    // const x = new XMLHttpRequest();
    // x.open("GET", fileUrl, true);
    // x.responseType = "blob";
    // x.onload = (e) => {
    //     let { status, readyState } = x;
    //     if (status === 200 && readyState === 4) {
    //         // 会创建一个 DOMString，其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
    //         const url = window.URL.createObjectURL(x.response);
    //         const a = document.createElement("a");
    //         a.href = url;
    //         a.download = row.drawingName.replace(new RegExp("#", "g"), "");
    //         a.click();
    //     } else {
    //         if (status === 404) {
    //             ElMessage({
    //                 type: "warning",
    //                 message: "文件不存在",
    //             });
    //         } else {
    //             ElMessage({
    //                 type: "warning",
    //                 message: "下载出错",
    //             });
    //         }
    //     }
    // };
    // x.send();
};

const dTypeChange = (val) => {
    let list1 = formData.value.drawingLists.filter((item) => {
        return item.drawingType == "中文";
    });
    let list2 = formData.value.drawingLists.filter((item) => {
        return item.drawingType == "英文";
    });
    // console.log(list)
    // if (list2 && list2.length > 1) {
    //     val["drawingType"] = "";
    //     ElMessage({
    //         type: "warning",
    //         message: "图纸类型只能一个英文图纸类型",
    //     });
    //     return;
    // }
    if (list1 && list1.length > 1) {
        val["drawingType"] = "";
        ElMessage({
            type: "warning",
            message: "图纸类型只能一个中文图纸类型",
        });
        return;
    }
    formData.value["drawingNum"] = "";
    if (list1 && list1[0]) {
        formData.value["drawingNum"] = list1[0].drawingName.split(".")[0];
    }
};

// 修改备注模块
const editReasonDialogShow = ref(false);
const contentCateOptions = ref([]);
const reasonCateOptions = ref([]);
const editReasonForm = ref({
    content: [],
    reason: [],
    detail: "",
});
const historyNoteColumns = ref([
    {
        prop: "ID",
        label: "序号",
        show: true,
        tableColumnProps: {
            sortable: false,
        },
    },
    {
        prop: "content",
        label: "更改内容",
        show: true,
        tableColumnProps: {
            sortable: false,
        },
    },
    {
        prop: "reason",
        label: "更改原因",
        show: true,
        tableColumnProps: {
            sortable: false,
        },
    },
    {
        prop: "detail",
        label: "详情说明",
        show: true,
        tableColumnProps: {
            sortable: false,
        },
    },
    {
        prop: "UpdatedAt",
        label: "更新时间",
        show: true,
        tableColumnProps: {
            sortable: false,
        },
    },
    {
        prop: "updateUser",
        label: "更新人",
        show: true,
        tableColumnProps: {
            sortable: false,
        },
    },
]);
const historyNoteTableData = ref([]);
const editStatus = ref("");
// 修改备注弹窗
const editReasonDialogFun = async (status) => {
   
    
    editStatus.value = status;
    editReasonDialogShow.value = true;
    editReasonForm.value = {
        content: [],
        reason: [],
        detail: "",
    };
    // 获取词典
    const options = await useDict("contentCate", "reasonCate");
    contentCateOptions.value = options.contentCate;
    reasonCateOptions.value = options.reasonCate;
};

function setShenpi(params) {
    let datas = {
        ddmsNum: formData.value.ddmsNum,
    };
    if (params == "同意") {
        datas.control = "1";
    } else if (params == "拒绝") {
        datas.control = "0";
    }
    shenpi(datas).then((res) => {
        if (res.code === 0) {
            ElMessage({
                type: "success",
                message: "审批成功",
            });

            // 获取当前URL
            const currentUrl = new URL(window.location.href);
            emitter.emit("closeThisPage");
            window.location.href =
                currentUrl.origin + "/#" + "/layout/ddmsSpecDrawing";
        }
    });
}

const shenbanComfirm = () => {
    editReasonDialogRef.value?.validate(async (valid) => {
        if (!valid) return;
        let submitForm = {};
        submitForm["modifyNotes"] = {
            content: editReasonForm.value.content.join(","),
            reason: editReasonForm.value.reason.join(","),
            detail: editReasonForm.value.detail || "",
        };
        submitForm["ddmsNum"] = route.query.ddmsNum;
        editComfirmdis.value = true
        updateDdmsSpecDrawingVersion(submitForm)
            .then((res) => {
                editReasonDialogShow.value = false;
                if (res.code == 0) {
                    ElMessage({
                        type: "success",
                        message: "升版成功",
                    });
                    setTimeout(() => {
                        editComfirmdis.value = false
                    }, 3000);
                    init();
                }
            })
            .catch((err) => {
                editReasonDialogShow.value = false;
            });
    });
};
// 编辑确认
const editComfirm = () => {

    editReasonDialogRef.value?.validate(async (valid) => {
        if (!valid) return;
        let submitForm = {};
        submitForm["ddmsNum"] = route.query.ddmsNum;
        submitForm["content"] = editReasonForm.value.content.join(",");
        submitForm["reason"] = editReasonForm.value.reason.join(",");
        submitForm["detail"] = editReasonForm.value.detail || "";
        
        createDdmsSpecDrawingNote(submitForm)
            .then((res) => {
                editReasonDialogShow.value = false;
                if (res.code == 0) {
                    isEditing.value = false;
                 
                    init();
                }
            })
            .catch((err) => {
                editReasonDialogShow.value = false;
            });
    });
};
const editComfirmdis = ref(false)
const shengban = async (params) => {
    editReasonDialogFun("shenban");
};

// 退回
const rollbackLoading = ref(false);
const rollbackFun = () => {
    rollbackLoading.value = true;
    rollbackDdmsSpecDrawingVersion({ ddmsNum: route.query.ddmsNum })
        .then((res) => {
            rollbackLoading.value = false;
            if (res.code == 0) {
                ElMessage({
                    type: "success",
                    message: "退回成功",
                });
                init();
            }
        })
        .catch((err) => {
            rollbackLoading.value = false;
        });
};

// 根据款式编号获取尺码和配件编号
const getSizesAndSpecsFun = (detail) => {
    let params = {
        styleNum: formData.value.styleNum,
        searchType: "ddmsSpecDrawing",
    };
    formData.value.selfMadeAccessory = [];
    displaySizeOptions.value = [];
    formData.value.displaySize = {};
    // 获取尺码
    getSizesAndSpecs(params).then((res) => {
        formData.value.selfMadeAccessory = res.data.specs; // 配件
        displaySizeOptions.value = res.data.sizes; // 尺码
    });
};

// 款式查询弹窗
const styleNumDialogShow = ref(false);
// 打开 新增、编辑
const openCreateAndEdit = () => {
    if (!route.query.ddmsNum) {
        styleNumDialogShow.value = true;
    }
};

// 关闭款式查询弹窗
function closeDialog(params) {
    styleNumDialogShow.value = false;
}

function selectStyleNum(params) {
    formData.value.styleNum = params.styleNum;
    if (!formData.value["extend"]) {
        formData.value["extend"] = {};
    }
    formData.value.extend["frameMaterials"] = params.frameMaterial;
    formData.value["gender"] = params.gender || "";
    formData.value["customerBrand"] = params.customerBrand || "";
    formData.value["series"] = params.series || "";
    formData.value["sbuNum"] = params.sbuNum || "";
    formData.value["localStyleNum"] = params.localStyleNum || "";
    formData.value["customerStyleNum"] = params.customerStyleNum || "";
    formData.value["cumstomerNum"] = params.cumstomerNum || "";
    getSizesAndSpecsFun(params);
    styleNumDialogShow.value = false;
}

onMounted(async () => {
    xToken.value = userStore.token;
    xUserId.value = userStore.userInfo.ID;

    // 获取字典
    await useDict(
        "drawingCharacterCate",
        "structure",
        "drawingCate",
        "drawingDataType"
    ).then((dict) => {
        dictOptions.value = Object.assign(dictOptions.value, dict);
    });
    // 获取审批流
    getWorkflowDefListFun();
    // 初始化分类
    formData.value.drawingCharacterCate =
        dictOptions.value.drawingCharacterCate[1].label;
    drawingCharacterCateChange();
});
</script>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");

.gva-form-box {
    :deep(.my-label) {
        width: 9%;
    }

    :deep(.my-content) {
        width: 16%;
    }
}

:deep(.el-descriptions__content) {
    word-break: break-all;
}
.el-table__cell {
    font-size: 16px;
}
:deep(.table-style-1) {
    .cell {
        font-size: 16px !important;
        padding-top: 6px !important;
        padding-bottom: 6px !important;
        // line-height: 32px;
        // height: 32px !important;
    }
}
:deep(.el-upload-dragger) {
    border: 1px dashed var(--el-color-primary);
    & > div {
        font-size: 18px !important;
    }
}
</style>
